package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.demo.entity.Order;
import com.example.demo.entity.Product;
import com.example.demo.entity.User;
import com.example.demo.service.OrderService;
import com.example.demo.service.ProductService;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    
    @Resource
    private OrderService orderService;
    
    @Resource
    private ProductService productService;
    
    @Resource
    private UserService userService;
    

    // 创建订单（简化版）
    @PostMapping
    public ResponseEntity<Map<String, Object>> createOrder(@RequestBody Map<String, Object> request) {
        try {
            // 获取请求参数
            List<Map<String, Object>> items = (List<Map<String, Object>>) request.get("items");
            String remark = (String) request.get("remark");
            // 从请求中获取用户ID
            Integer userId = (Integer) request.get("userId");
            
            System.out.println("创建订单请求参数: " + request);
            System.out.println("获取到的用户ID: " + userId + ", 类型: " + (userId != null ? userId.getClass().getSimpleName() : "null"));
            
            if (items == null || items.isEmpty()) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "订单项不能为空"
                ));
            }
            
            if (userId == null) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "用户ID不能为空"
                ));
            }
            
            // 生成订单ID和订单号
            String orderId = "order_" + System.currentTimeMillis();
            String orderNumber = generateOrderNumber();
            
            // 计算订单总金额 - 根据商品信息计算
            BigDecimal totalAmount = calculateTotalAmount(items, remark);
            
            // 创建订单
            Order order = new Order();
            order.setId(orderId);
            order.setOrderNumber(orderNumber);
            order.setTotalAmount(totalAmount);
            order.setStatus("pending"); // 待支付
            order.setRemark(remark);
            order.setUserId(userId); // 直接设置用户ID
            
            // 保存订单
            boolean saved = orderService.save(order);
            
            if (saved) {
                // 返回订单信息
                Map<String, Object> orderData = new HashMap<>();
                orderData.put("id", order.getId());
                orderData.put("orderNumber", order.getOrderNumber());
                orderData.put("totalAmount", order.getTotalAmount());
                orderData.put("status", order.getStatus());
                orderData.put("createdAt", order.getCreatedAt());
                
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "订单创建成功",
                        "data", orderData
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "订单创建失败"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "订单创建失败: " + e.getMessage()
            ));
        }
    }
    
    // 根据ID获取订单详情
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getOrderById(@PathVariable String id) {
        try {
            Order order = orderService.getById(id);
            
            if (order != null) {
                // 模拟订单项数据
                Map<String, Object> orderData = new HashMap<>();
                orderData.put("id", order.getId());
                orderData.put("orderNumber", order.getOrderNumber());
                orderData.put("totalAmount", order.getTotalAmount());
                orderData.put("status", order.getStatus());
                orderData.put("paymentMethod", order.getPaymentMethod());
                orderData.put("paymentOrderId", order.getPaymentOrderId());
                orderData.put("paidAt", order.getPaidAt());
                orderData.put("remark", order.getRemark());
                orderData.put("createdAt", order.getCreatedAt());
                orderData.put("updatedAt", order.getUpdatedAt());
                
                // 模拟订单项
                Map<String, Object> orderItem = new HashMap<>();
                orderItem.put("productId", "prod_001");
                orderItem.put("productName", "基础聊天套餐");
                orderItem.put("productPrice", new BigDecimal("29.90"));
                orderItem.put("quantity", 1);
                orderItem.put("subtotal", new BigDecimal("29.90"));
                
                orderData.put("orderItems", List.of(orderItem));
                
                return ResponseEntity.ok(Map.of(
                        "success", true,
                        "message", "获取订单详情成功",
                        "data", orderData
                ));
            } else {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "订单不存在"
                ));
            }
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "获取订单详情失败: " + e.getMessage()
            ));
        }
    }
    
    // 创建支付
    @PostMapping("/{id}/payment")
    public ResponseEntity<Map<String, Object>> createPayment(@PathVariable String id, @RequestBody Map<String, Object> request) {
        try {
            Order order = orderService.getById(id);
            
            if (order == null) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "订单不存在"
                ));
            }
            
            if (!"pending".equals(order.getStatus())) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "订单状态不正确，无法支付"
                ));
            }
            
            String paymentMethod = (String) request.get("paymentMethod");
            
            // 生成支付订单号
            String paymentOrderId = "pay_" + System.currentTimeMillis() + "_" + (int)(Math.random() * 1000);
            
            // 一次性更新订单信息
            order.setPaymentMethod(paymentMethod);
            order.setPaymentOrderId(paymentOrderId);
            order.setStatus("paid");
            order.setPaidAt(LocalDateTime.now());
            orderService.updateById(order);
            
            // 生成支付信息
            Map<String, Object> paymentData = new HashMap<>();
            paymentData.put("orderId", order.getId());
            paymentData.put("orderNumber", order.getOrderNumber());
            paymentData.put("amount", order.getTotalAmount());
            paymentData.put("paymentMethod", paymentMethod);
            paymentData.put("paymentOrderId", paymentOrderId);
            
            // 生成二维码数据（模拟）
            String qrCodeData = generateQRCodeData(paymentMethod, paymentOrderId, order.getTotalAmount());
            paymentData.put("qrCode", qrCodeData);
            paymentData.put("expireTime", LocalDateTime.now().plusMinutes(15));
            
            // 自动更新用户权益（简化处理）
            try {
                updateUserBenefitsFromOrder(order);
            } catch (Exception e) {
                System.err.println("自动更新用户权益失败: " + e.getMessage());
            }
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "支付信息创建成功",
                    "data", paymentData
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "创建支付失败: " + e.getMessage()
            ));
        }
    }
    
    // 获取用户订单列表
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserOrders(@PathVariable Integer userId) {
        try {
            LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Order::getUserId, userId)
                       .orderByDesc(Order::getCreatedAt);
            
            List<Order> orders = orderService.list(queryWrapper);
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "获取订单列表成功",
                    "data", orders
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "获取订单列表失败: " + e.getMessage()
            ));
        }
    }
    
    
    // 获取订单权益信息
    @GetMapping("/{id}/benefits")
    public ResponseEntity<Map<String, Object>> getOrderBenefits(@PathVariable String id) {
        try {
            Order order = orderService.getById(id);
            if (order == null) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "订单不存在"
                ));
            }
            
            // 从订单备注中解析商品信息
            String remark = order.getRemark();
            Product product = null;
            
            if (remark != null && remark.contains("基础聊天套餐")) {
                product = productService.getById("prod_001");
            } else if (remark != null && remark.contains("高级聊天套餐")) {
                product = productService.getById("prod_002");
            } else if (remark != null && remark.contains("VIP会员")) {
                product = productService.getById("prod_004");
            } else {
                // 默认使用基础套餐
                product = productService.getById("prod_001");
            }
            
            if (product == null) {
                return ResponseEntity.ok(Map.of(
                        "success", false,
                        "message", "商品信息不存在"
                ));
            }
            
            // 构建权益信息
            Map<String, Object> benefits = new HashMap<>();
            benefits.put("token", product.getToken());
            benefits.put("validityDays", product.getValidityDays());
            benefits.put("productName", product.getName());
            benefits.put("productType", product.getType());
            
            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "获取订单权益成功",
                    "data", benefits
            ));
        } catch (Exception e) {
            return ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "获取订单权益失败: " + e.getMessage()
            ));
        }
    }
    
    // 从订单自动更新用户权益
    private void updateUserBenefitsFromOrder(Order order) {
        try {
            // 获取用户信息 - 支持数字ID和账号查询
            User user = findUserByIdOrAccount(order.getUserId());
            if (user == null) {
                System.err.println("用户不存在: " + order.getUserId());
                return;
            }
            
            // 从订单备注中解析商品信息
            String remark = order.getRemark();
            Product product = null;
            
            if (remark != null && remark.contains("基础聊天套餐")) {
                product = productService.getById("prod_001");
            } else if (remark != null && remark.contains("高级聊天套餐")) {
                product = productService.getById("prod_002");
            } else if (remark != null && remark.contains("VIP会员")) {
                product = productService.getById("prod_004");
            } else {
                // 默认使用基础套餐
                product = productService.getById("prod_001");
            }
            
            if (product != null) {
                updateUserBenefits(user, product);
                userService.updateById(user);
                System.out.println("用户权益更新成功: 用户ID=" + user.getId() + 
                    ", Token数=" + user.getTotalTokens() + 
                    ", 有效期=" + user.getTotalValidityDays());
            } else {
                System.err.println("商品信息不存在");
            }
        } catch (Exception e) {
            System.err.println("从订单更新用户权益失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    // 用户权益计算逻辑
    private void updateUserBenefits(User user, Product product) {
        LocalDateTime now = LocalDateTime.now();
        
        // 更新token数量
        if (product.getToken() != null) {
            if (product.getToken() == -1) {
                // 无限制token
                user.setTotalTokens(-1);
            } else {
                // 累加token
                if (user.getTotalTokens() == null || user.getTotalTokens() == -1) {
                    user.setTotalTokens(product.getToken());
                } else {
                    user.setTotalTokens(user.getTotalTokens() + product.getToken());
                }
            }
        }
        
        // 更新有效期
        if (product.getValidityDays() != null) {
            if (product.getValidityDays() == -1) {
                // 永久有效
                user.setTotalValidityDays(-1);
                user.setExpiresAt(null);
            } else {
                // 计算新的过期时间
                LocalDateTime newExpiresAt;
                if (user.getExpiresAt() == null || user.getExpiresAt().isBefore(now)) {
                    // 如果当前没有权益或已过期，从当前时间开始计算
                    newExpiresAt = now.plusDays(product.getValidityDays());
                } else {
                    // 如果当前权益未过期，在现有基础上延长
                    newExpiresAt = user.getExpiresAt().plusDays(product.getValidityDays());
                }
                user.setExpiresAt(newExpiresAt);
                
                // 更新总有效天数
                if (user.getTotalValidityDays() == null || user.getTotalValidityDays() == -1) {
                    user.setTotalValidityDays(product.getValidityDays());
                } else {
                    user.setTotalValidityDays(user.getTotalValidityDays() + product.getValidityDays());
                }
            }
        }
        
        // 更新权益最后更新时间
        user.setLastBenefitUpdate(now);
    }
    
    // 生成真实二维码数据
    private String generateQRCodeData(String paymentMethod, String paymentOrderId, BigDecimal amount) {
        if ("wechat".equals(paymentMethod)) {
            return "weixin://wxpay/bizpayurl?pr=" + paymentOrderId + "&amount=" + amount.multiply(new BigDecimal(100)).intValue();
        } else if ("alipay".equals(paymentMethod)) {
            return "alipays://platformapi/startapp?appId=20000067&url=" + paymentOrderId + "&amount=" + amount;
        } else {
            return "payment://" + paymentMethod + "/" + paymentOrderId + "?amount=" + amount;
        }
    }
    
    // 生成订单号
    private String generateOrderNumber() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String random = String.valueOf((int)(Math.random() * 1000));
        return "ORD" + timestamp + random;
    }
    
    // 查找用户（支持ID和账号查询）
    private User findUserByIdOrAccount(Integer userId) {
        // 直接按ID查询
        User user = userService.getById(userId.longValue());
        if (user != null) {
            return user;
        }
        
        // 如果按ID查询失败，按账号查询（将ID转换为字符串作为账号）
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getAccount, String.valueOf(userId));
        return userService.getOne(queryWrapper);
    }
    
    // 计算订单总金额
    private BigDecimal calculateTotalAmount(List<Map<String, Object>> items, String remark) {
        BigDecimal total = BigDecimal.ZERO;
        
        // 首先尝试从订单项中计算总金额
        if (items != null && !items.isEmpty()) {
            for (Map<String, Object> item : items) {
                Object priceObj = item.get("price");
                Object quantityObj = item.get("quantity");
                
                BigDecimal price = BigDecimal.ZERO;
                int quantity = 1;
                
                if (priceObj instanceof Number) {
                    price = new BigDecimal(priceObj.toString());
                }
                if (quantityObj instanceof Number) {
                    quantity = ((Number) quantityObj).intValue();
                }
                
                total = total.add(price.multiply(new BigDecimal(quantity)));
            }
        }
        
        // 如果从订单项无法计算，则根据备注中的商品名称从数据库获取价格
        if (total.compareTo(BigDecimal.ZERO) == 0 && remark != null) {
            Product product = null;
            
            if (remark.contains("基础聊天套餐")) {
                product = productService.getById("prod_001");
            } else if (remark.contains("高级聊天套餐")) {
                product = productService.getById("prod_002");
            } else if (remark.contains("无限聊天套餐")) {
                product = productService.getById("prod_003");
            } else if (remark.contains("VIP会员")) {
                product = productService.getById("prod_004");
            } else if (remark.contains("企业版")) {
                product = productService.getById("prod_005");
            }
            
            if (product != null && product.getPrice() != null) {
                total = product.getPrice();
            }
        }
        
        // 如果还是无法计算，默认返回0
        return total;
    }
}
